package ms.sudoku;

import java.util.Comparator;
import java.util.List;

import ms.sudoku.technique.EliminationTechnique;

/**
 * Used to compare the difficulty of two generated puzzles.
 */
public class SolverResultsComparator implements Comparator<SolverResults> {
	private List<EliminationTechnique> _techniqueList;

	public SolverResultsComparator(List<EliminationTechnique> techniqueList) {
		if (techniqueList == null)
			throw new NullPointerException("techniques");

		_techniqueList = techniqueList;
	}

	public int compare(SolverResults a, SolverResults b) {
		if (a == b) {
			return 0;
		} else if (a == null) {
			return 1;
		} else if (b == null) {
			return -1;
		} else {
			// First compare by number of decision points
			int diff = a.getNumberOfDecisionPoints() - b.getNumberOfDecisionPoints();
			if (diff != 0) {
				return diff;
			}

			/*
			 * Then compare each by technique, starting with the most difficult.
			 */
			for (int i = _techniqueList.size() - 1; i >= 0; --i) {
				Integer firstUse = a.getUseOfTechniques().get(_techniqueList.get(i));
				Integer secondUse = b.getUseOfTechniques().get(_techniqueList.get(i));
				if (firstUse != null && secondUse != null) {
					diff = firstUse - secondUse;
					if (diff != 0) {
						return diff;
					}
				} else if (firstUse != null) {
					return 1;
				} else if (secondUse != null) {
					return -1;
				}

			}
		}
		// SolverResults are equal if they have the exact same number of
		// decision points
		// and usage of each technique.
		return 0;
	}

}